﻿using System;
using System.Net;
using System.Threading.Tasks;

namespace Cavy.UdpClient.SystemUdpClient
{
    public class TransportSystemUdpClient : Transport
    {
        private System.Net.Sockets.UdpClient _udpClient;

        public override int Bind(int port = 0)
        {
            _udpClient = new System.Net.Sockets.UdpClient(port);
            return port;
        }
        
        public override bool EnableBroadcast
        {
            set => _udpClient.EnableBroadcast = value;
            get => _udpClient.EnableBroadcast;
        }

        public override int ReceiveBufferSize
        {
            set => _udpClient.Client.ReceiveBufferSize = value;
            get => _udpClient.Client.ReceiveBufferSize;
        }

        public override void Connect(string address, int port)
        {
            CallOnConnected();
        }

        public override void Close()
        {
            _udpClient.Close();
        }

        public override void Dispose()
        {
            _udpClient?.Close();
            _udpClient?.Dispose();
        }

        public async override void ReceiveAsync()
        {
            if(IsReceiving) return;
            IsReceiving = true;
            while (IsPlaying)
            {
                var result = await _udpClient.ReceiveAsync();
                UdpResult udpResult = new UdpResult()
                {
                    Buffer = result.Buffer,
                    RemoteEndPoint = new IpEndPoint()
                    {
                        Address = result.RemoteEndPoint.Address.ToString(),
                        Port = result.RemoteEndPoint.Port
                    }
                };
                CallOnReceived(udpResult);
            }
        }

        public override void Send(byte[] data, int dataLength, string host, int port)
        {
            _udpClient.Send(data, dataLength, host, port);
        }
    }
}